
import { CreateBannerDto, UpdateBannerDto, QueryBannerDto, DeleteBannerDto, SelectOneBannerDto, SortBannerDto } from '@/dto/banner.dto';
import bannerRepository from '@/repositories/banner.repository';


class BannerService {

    /**
     * 创建
     * @param data  
     * @returns 
     */

    async add(data: CreateBannerDto) {
        // 检查是否已存在
        const findOne = await bannerRepository.bannerExists(data.title);
        if (findOne) {
            if (findOne.title == data.title) {
                throw new Error('标题已存在！');
            }

        }
        // 创建
        return bannerRepository.create(data);
    }
    async update(data: UpdateBannerDto) {
        // 1. 检查是否存在
        const existingCategory = await bannerRepository.findById(data.id);
        if (!existingCategory) {
            throw new Error("数据不存在")
        }


        const findOne = await bannerRepository.findExcludeId(data);
        if (findOne) {
            if (findOne.title == data.title) {
                throw new Error('名称已存在！');
            }

        }
        // 更新
        return bannerRepository.update(data);
    }

    async selectOne(reqData: SelectOneBannerDto) {
        return bannerRepository.findById(reqData.id)


    }

    async selectList(reqData: QueryBannerDto) {
        return bannerRepository.selectList(reqData)


    }
    async delete(reqData: DeleteBannerDto) {
        let res = await bannerRepository.delete(reqData);
        if (!res) {
            throw new Error("id不存在，无删除记录！")
        }
        return res


    }
    async sort(reqData: SortBannerDto) {
        let res = await bannerRepository.sort(reqData);
        return res


    }

}

export default new BannerService();

